/*****************************************************************************************************
* 模块:Routing Plan
* 开发人：Fu Haisha
* 描述：TSR新增Routing plan,可以排序和删除Routing plan
******************************************************************************************************/
public class AddRoutingPlan {
    
    public List<Account> accList{get;set;}
    public String[] checkValue{get;set;}
    public String[] checkOrderValue{get;set;}
    public List<SelectOption> leftItems;
    public List<SelectOption> rightItems;
    public List<RoutingPlan__c> rpLoadData{get;set;}
    private Routing_Plan_And_Visit__c rpv;
    public Boolean isDisplay{get;set;}
        
    public String idStr
    {  
      get{   
                return System.currentPageReference().getParameters().get('id');    
         }     
      set;}  
   
    public List<SelectOption> getLeftItems(){
        return leftItems;
    }
    public List<SelectOption> getRightItems(){
        return rightItems;
    }
    public void setRightItems(List<SelectOption> options){
        rightItems = options;
    }
    
    public AddRoutingPlan()
    { 
        try
        {
           rpv=new Routing_Plan_And_Visit__c();
           rpv=[select Visit_Date__c from Routing_Plan_And_Visit__c where Id=:idStr];
        }
       catch(Exception ex)
       {}
        isDisplay=false;
       /* Integer Count=rpv.Visit_Date__c.monthsBetween(Date.toDay());
        if(Count<0)
            isDisplay=true;
        else
            isDisplay=false;*/
        Profile p=[select Id,Name from  Profile where Id=:UserInfo.getProfileId()];
        if(p.Name=='系统管理员' || p.Name=='System Administrator')
        {
            if(rpv.Visit_Date__c>System.ToDay())
               isDisplay=true;
            else
               isDisplay=false; 
        }
        else if(p.Name=='Sales Rep - Trade')
        {
            if(rpv!=NULL || rpv.Visit_Date__c!=NULL)
            {
                Integer count=Date.toDay().monthsBetween(rpv.Visit_Date__c);
                  if(count>0)
                    isDisplay=true;
                    else
                    isDisplay=false;    
            }  
                       
        }
        else
        {
                isDisplay=false;
        }
      
        
        rpLoadData=new List<RoutingPlan__c>();
        if(leftItems==Null)
           leftItems=new List<SelectOption>();
        if(rightItems==NULL)
            rightItems=new List<SelectOption>();                
        for(Account acc:[select Id,Name,OutletCode__c from Account where ownerId=:UserInfo.getUserId() and Active_Status__c='正常营业' and Id not in(select OutletName__c from RoutingPlan__c where RoutingPlanAndVisit__c=:idStr)])
        {
            leftItems.add(new SelectOption(acc.Id,acc.OutletCode__c+'    '+acc.Name));
        }
        for(RoutingPlan__c acc:[select OutletName__c,OutletName__r.Name,OutletName__r.Id,OutletName__r.OutletCode__c,RoutingPlanAndVisit__r.Visit_Date__c from RoutingPlan__c where RoutingPlanAndVisit__c=:idStr])
        {
            rpLoadData.add(acc);

            if(acc.OutletName__r.Id!=NULL || acc.OutletName__r.Name!=NULL)
            {
                rightItems.add(new SelectOption(acc.OutletName__r.Id,acc.OutletName__r.OutletCode__c+'    '+acc.OutletName__r.Name));
            }
        }
      
        
        checkValue=new String[]{};     
        checkOrderValue=new String[]{};      
      
    }
    
    public PageReference Add()
    {
        //if(rightItems!=NULL)
         //   rightItems.clear();
        if(checkValue!=NULL)
        {
            for(Integer i=0; i<leftItems.size(); i++)
            {
                for(String str:checkValue)
               {
               
                    if(leftItems[i].getValue()==str)
                    {
                        rightItems.add(leftItems[i]);
                        leftItems.remove(i);
                    }
                }
            }
        }
        return null;
    }
    
    public PageReference Up()
    {
        for(Integer i=1; i < rightItems.size(); i++)
        {
            for(String str:checkOrderValue)
            {
                if(str==rightItems[i].getValue())
                {
                      String selText = rightItems[i].getLabel();
                      String selValue = rightItems[i].getValue();
                                            
                      rightItems[i].setLabel(rightItems[i-1].getLabel());
                      rightItems[i].setValue(rightItems[i-1].getValue());
                      //rightItems[i].selected = false;
                      
                      rightItems[i-1].setLabel(selText);
                      rightItems[i-1].setValue(selValue);
                      //sel.options[i-1].selected=true;
                
                }
            }
         }

        return null;
    }
    public PageReference Down()
    {
        
        for(Integer i=rightItems.size()-2;i>=0; i--)
        {
            for(String str:checkOrderValue)
            {
                if(str==rightItems[i].getValue())
                {
                      String selText = rightItems[i].getLabel();
                      String selValue = rightItems[i].getValue();
                                            
                      rightItems[i].setLabel(rightItems[i+1].getLabel());
                      rightItems[i].setValue(rightItems[i+1].getValue());
                      //rightItems[i].selected = false;
                      
                      rightItems[i+1].setLabel(selText);
                      rightItems[i+1].setValue(selValue);
                      //sel.options[i-1].selected=true;
                
                }
            }
         }

        return null;

    }
   public PageReference Remove()
   {
        if(checkOrderValue != NULL)
        {
            for(String str:checkOrderValue)
            {
                for(Integer i=0;i<rightItems.size();i++)
                {
                    if(rightItems[i].getValue()==str)
                    {
                        leftItems.add(rightItems[i]);
                        rightItems.remove(i);
                    }
                }
             }
        }
        return null;
    }
    
    public PageReference Save()
    {
       List<RoutingPlan__c> rpList=new List<RoutingPlan__c>();
        //system.debug('Right before for Loop: ' + rightItems.size());
        
        Date dt=rpv.Visit_Date__c;
        Integer Minute=0;
        DateTime visitDt;//=DateTime.newInstance(dt.year(),dt.month(),dt.day(),8,Minute,1);
        for(Integer i=0; i<rightItems.size(); i++)
        {
               // system.debug('In for Loop');
               visitDt=DateTime.newInstance(dt.year(),dt.month(),dt.day(),8,Minute,1);
               SelectOption so=rightItems[i];
               Account tempRp=[select Name from Account where Id=:so.getValue()];
               RoutingPlan__c rp=new RoutingPlan__c(Name=tempRp.Name,RoutingPlanAndVisit__c=idStr,Sort__c=i+1,OutletName__c=so.getValue(),StartDateTime__c=visitDt,EndDateTime__c=visitDt.addMinutes(30));
               Minute+=30;
               rpList.add(rp);
        }
       
        if(rpList!=NULL) 
        {
            // system.debug('Right before insert');
            if(rpLoadData.size()>0)
            {
               try
               {
                    delete rpLoadData;
               }
               catch(Exception es)
              {}
                /*delete lEvent;*/
            }            
                insert rpList;
           }
        
        pageReference pr = new pageReference('/'+ idStr);
        pr.setredirect(true); 
        return pr;
       //   return null;  
    }
    public PageReference ViewReport()
    {
        String url=RoutingPlanReportUrl__c.getValues('RoutingPlanCount').Url__c;
         Date StartD=rpv.Visit_Date__c;
         Date EndD=StartD.addMonths(1);
         pageReference pr = new pageReference(url+'?pv0='+StartD.month()+'/1/'+StartD.year()+'&pv1='+EndD.month()+'/1/'+EndD.year());
       
         pr.setredirect(true); 
        return pr;
    }
    public PageReference Cancel()
    {
        pageReference pr = new pageReference('/'+ idStr);
        pr.setredirect(true); 
        return pr;    
    }
    @future
    public static void TestRun()
    {
         Profile p = [select id from profile where name='System Administrator' or Name='系统管理员'];
        User u = new User(alias = 'standtss', email='standarduser@testorgss.com',
        emailencodingkey='UTF-8', lastname='Testing', languagelocalekey='en_US',
        localesidkey='en_US', profileid = p.Id,
        timezonesidkey='America/Los_Angeles', username='standardusers@testorg.com');
        System.runAs(u)
        {
            Routing_Plan_And_Visit__c tr=new Routing_Plan_And_Visit__c(Visit_Date__c=Date.today().addMonths(1));
            insert tr;
            
            Account acc=new Account();
            acc.Name='test';
            acc.Channel__c='Cash & Carry';
            acc.Contact__c='aaa';
            acc.No_of_checkout__c=22;
            acc.ContactPhoneNumber__c='1234567456';
            acc.OwnerId=UserInfo.getUserId();
            insert acc;
            
            Account acc2=new Account();
            acc2.Name='test2';
            acc2.Channel__c='Cash & Carry';
            acc2.Contact__c='aaa';
            acc2.No_of_checkout__c=22;
            acc2.ContactPhoneNumber__c='1234567456';
            acc2.OwnerId=UserInfo.getUserId();
            insert acc2;
            
            RoutingPlan__c rp=new RoutingPlan__c();
            Date d=tr.Visit_Date__c;
            rp.StartDateTime__c=DateTime.newInstance(d.year(),d.month(),d.day(),8,8,8);
            rp.EndDateTime__c=DateTime.newInstance(d.year(),d.month(),d.day(),9,9,9);
            rp.RoutingPlanAndVisit__c=tr.Id;
            rp.OutletName__c=acc.Id;
            insert rp;
            
            RoutingPlan__c rp2=new RoutingPlan__c();
            Date d2=tr.Visit_Date__c;
            rp2.StartDateTime__c=DateTime.newInstance(d2.year(),d2.month(),d2.day(),8,8,8);
            rp2.EndDateTime__c=DateTime.newInstance(d2.year(),d2.month(),d2.day(),9,9,9);
            rp2.RoutingPlanAndVisit__c=tr.Id;
            rp2.OutletName__c=acc.Id;
            insert rp2;
            
            /*RoutingPlan__c r2=[select Id, RoutingPlanAndVisit__c,OutletName__c,StartDateTime__c,EndDateTime__c from RoutingPlan__c where RoutingPlanAndVisit__c=:tr.Id ]; 
            r2.StartDateTime__c=DateTime.now().addMinutes(22);
            r2.EndDateTime__c=DateTime.now().addMinutes(40);
            update r2;*/
            
            System.currentPageReference().getParameters().put('id', tr.Id); 
            AddRoutingPlan add=new AddRoutingPlan();
            add.getLeftItems();
            add.getRightItems();
            //List<SelectOption> r=new List<SelectOption>();
            //r.add(new SelectOption(acc.Id,acc.Name));
            //add.setRightItems(r);
            add.checkValue=new String[]{acc.Id};
            add.Add();
            
            add.checkOrderValue=new String[]{acc.Id};
            add.Up();
            //add.checkOrderValue=new String[]{acc.Id};
            add.Down();
            
            List<SelectOption> re=new List<SelectOption>();
            re.add(new SelectOption(acc.Id,acc.Name));
            add.setRightItems(re);
            add.Remove();
            add.Cancel();
            add.Save();
        }
        //delete r2;
    }
    static testmethod void Test()
    {
       //AddRoutingPlan a=new AddRoutingPlan();
       AddRoutingPlan.TestRun();
    }
}